package handler

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"shop_srvs/goods_srv/global"
	"shop_srvs/goods_srv/model"
	"shop_srvs/goods_srv/proto"
)

// 品牌
func (g *GoodsServer) BrandList(ctx context.Context, req *proto.BrandFilterRequest) (*proto.BrandListResponse, error) {
	var brands []model.Brands
	brandListResponse := proto.BrandListResponse{}

	result := global.DB.Scopes(Paginate(int(req.Pn), int(req.PSize))).Find(&brands)
	if result.Error != nil {
		return nil, result.Error
	}

	var brandResponses []*proto.BrandInfoResponse
	for _, brand := range brands {
		brandResponses = append(brandResponses, &proto.BrandInfoResponse{
			Id:   brand.ID,
			Name: brand.Name,
			Logo: brand.Logo,
		})
	}
	brandListResponse.Total = int32(result.RowsAffected)
	brandListResponse.Data = brandResponses
	return &brandListResponse, nil
}
func (g *GoodsServer) CreateBrand(ctx context.Context, req *proto.BrandRequest) (*proto.BrandInfoResponse, error) {
	brands := model.Brands{}
	if result := global.DB.Where("name=?", req.Name).First(&brands); result.RowsAffected == 1 {
		return nil, status.Error(codes.AlreadyExists, "品牌已存在")
	}
	brands.Name = req.Name
	brands.Logo = req.Logo
	if res := global.DB.Save(&brands); res.Error != nil {
		return nil, status.Errorf(codes.Internal, res.Error.Error())
	}
	return &proto.BrandInfoResponse{Id: brands.ID}, nil
}
func (g *GoodsServer) DeleteBrand(ctx context.Context, req *proto.BrandRequest) (*emptypb.Empty, error) {
	if res := global.DB.Delete(&model.Brands{}, req.Id); res.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "品牌不存在")
	}
	return &emptypb.Empty{}, nil
}
func (g *GoodsServer) UpdateBrand(ctx context.Context, req *proto.BrandRequest) (*emptypb.Empty, error) {
	brands := model.Brands{}
	if res := global.DB.First(&brands, req.Id); res.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "品牌不存在")
	}

	brands.Name = req.Name
	brands.Logo = req.Logo
	if res := global.DB.Save(&brands); res.Error != nil {
		return nil, status.Errorf(codes.Internal, res.Error.Error())
	}
	return &emptypb.Empty{}, nil
}
